package com.flash.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.flash.Cache.RedisData;
import com.flash.constant.RedisKeyConstant;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.flash.constant.MessageConstant;
import com.flash.context.BaseContext;
import com.flash.dto.*;
import com.flash.entity.*;
import com.flash.exception.AddressBookBusinessException;
import com.flash.exception.OrderBusinessException;
import com.flash.exception.ShoppingCartBusinessException;
import com.flash.mapper.*;
import com.flash.result.PageResult;
import com.flash.service.OrderService;
import com.flash.utils.BaiDuMapUtils;
import com.flash.utils.Output;
import com.flash.utils.WeChatPayUtil;
import com.flash.vo.OrderPaymentVO;
import com.flash.vo.OrderStatisticsVO;
import com.flash.vo.OrderSubmitVO;
import com.flash.vo.OrderVO;
import com.flash.webSocket.WebSocketServer;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import nonapi.io.github.classgraph.json.JSONUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.PipedReader;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private BaiDuMapUtils baiDuMapUtils;
    @Autowired
    private AddressBookMapper addressMapper;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) throws IOException {
        /*
        *处理各种业务异常
        * 购物车数据为空
        * 用户派送地址异常
        */

        String address = addressMapper.getAddressById(ordersSubmitDTO.getAddressBookId()).getAddress();
        baiDuMapUtils.couldDelivery(address);


        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);

        if (list == null || list.isEmpty()){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null){
            /*抛出业务异常*/
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        /*向订单表插入一条数据*/
        Orders orders = new Orders();

        //设置值
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
//        设置订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
//        设置userId
        orders.setUserId(BaseContext.getCurrentId());
//      设置下单时间
        orders.setOrderTime(LocalDateTime.now());
//      设置支付状态
        orders.setPayStatus(Orders.UN_PAID);
        //设置订单号码，使用时间戳
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        //设置地址
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName());
        //设置电话
        orders.setPhone(addressBook.getPhone());
        //设置收货人姓名
        orders.setConsignee(addressBook.getConsignee());
        //设置用户名
        orders.setUserName(userMapper.getById(orders.getUserId()).getName());

        orderMapper.insert(orders);
        List<OrderDetail> orderDetails = new ArrayList<>();
        /*向订单明细表插入n条数据,遍历获取购物车数据*/
        for (ShoppingCart cart : list){
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setNumber(cart.getNumber());
            System.out.println(cart.getNumber());
            orderDetail.setOrderId(orders.getId());//设置当前订单的订单id

            orderDetails.add(orderDetail);
        }
        Output.Output(orderDetails,"订单信息");

        orderDetailMapper.insertBatch(orderDetails);

        /*下单成功之后，清空用户的购物车数据*/
        shoppingCartMapper.cleanChart(BaseContext.getCurrentId());
        /*返回结果*/

        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        /*// 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);


        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );



        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;*/
        Orders orders = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());

        /**
         * 支付状态 0未支付 1已支付 2退款
         */
        orders.setPayStatus(Orders.PAID);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setCheckoutTime(LocalDateTime.now());
        orderMapper.update(orders);

        Map map =new HashMap<>();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号"+ordersPaymentDTO.getOrderNumber());

        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
        return null;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        log.info("支付成功");

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }

    /**
     * 查询历史订单
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult getPageResult(int page, int pageSize, Integer status) {

        PageHelper.startPage(page,pageSize);
        OrdersPageQueryDTO pageQueryDTO = new OrdersPageQueryDTO();
        Long userId = BaseContext.getCurrentId();
        //按照时间顺序排序，从新到旧，也就是从小到大，递增模式查询，查询出订单时间<1个月的
        //所以要求status满足，用户满足，时间满足，三个条件
        pageQueryDTO.setUserId(userId);
        pageQueryDTO.setStatus(status);

        Page<Orders> ordersPage = orderMapper.getOrdersByCondition(pageQueryDTO);

        List<OrderVO> orderVOS = new ArrayList<>();

        if (ordersPage != null && !ordersPage.isEmpty()){
            //仅仅有订单信息，并没有订单对应的菜品信息，所以我们要增加菜品的相关内容,
            ordersPage.forEach(orders -> {
                List<OrderDetail>details =  orderDetailMapper.getDetailsByOrderId(orders.getId());
                //将其封装在OrderVO中
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                orderVO.setOrderDetailList(details);
                orderVOS.add(orderVO);
            });
        }
        return new PageResult(ordersPage.getTotal(),orderVOS);
    }



    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        //先去缓存中查数据
        //先去订单表查询订单数据
        Orders orders = getById(id);
        //根据订单id查询OrderDetail
        List<OrderDetail> orderDetails = orderDetailMapper.getDetailsByOrderId(id);
        //进行OrderVO的封装

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetails);

        return orderVO;
    }

    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void cancel(Long id) {
        /*查询订单是否存在*/
        Orders orders = getById(id);
        Output.Output(id + orders.toString(),"查询订单是否存在");
        if (orders != null){
            /*
             * 订单状态
             *  1待付款：可以取消,直接退单,将数据库中对应的数据删除
             *  2待接单：取消退款，微信自动退款
             *  3已接单：自动退款
             *  4派送中：手动退款
             *  5已完成：手动退款
             *  6已取消
             */
            /*如果未接单那么可以取消,否则抛出异常*/
            if (orders.getStatus() > Orders.TO_BE_CONFIRMED){
                throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
            }
            /*如果是已经付款，那么进行退款*/
            if (orders.getStatus() == Orders.TO_BE_CONFIRMED){
                log.info("已经退款");
                //支付状态修改为 退款
                orders.setPayStatus(Orders.REFUND);
            }
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orderMapper.update(orders);
        }
    }


    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        /*将订单信息复制过来*/
        System.out.println(id);
        Long userId = BaseContext.getCurrentId();
        List<OrderDetail> details = orderDetailMapper.getDetailsByOrderId(id);
        System.out.println(details);
        /*重新构建一个购物车信息*/
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        for (OrderDetail detail : details) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(detail,shoppingCart);
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCarts.add(shoppingCart);
        }
        System.out.println("shoppingCarts = " + shoppingCarts);
        shoppingCartMapper.insertBatch(shoppingCarts);
    }

    /**
     * 实现订单条件查询
     * @param ordersPageQueryDTO
     * @return
     */

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.getOrdersByCondition(ordersPageQueryDTO);
        List<OrderVO> orderVOS = new ArrayList<>();
        page.forEach(orders ->{
            OrderVO orderVO = new OrderVO();
            StringBuilder stringBuilder = new StringBuilder();
            List<OrderDetail> detailsByOrderId = orderDetailMapper.getDetailsByOrderId(orders.getId());
            detailsByOrderId.forEach(d->{
                stringBuilder.append(d.getName().toString());
            });
            orderVO.setOrderDishes(stringBuilder.toString());
            BeanUtils.copyProperties(orders,orderVO);
            orderVOS.add(orderVO);
        });

        return new PageResult(page.getTotal(),orderVOS);
    }
    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }
    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();

        orderMapper.update(orders);
    }
    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO){
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            log.info("申请退款");
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    /**
     * 取消订单
     *
     * @param ordersCancelDTO
     */
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            log.info("申请退款");
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = getById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        Orders ordersDB = getById(id);

        if (ordersDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号："+ordersDB.getNumber());

        String jsonObject = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonObject);

    }

    private Orders getById(Long id){
        //先去缓存里面查
        String json = (String) redisTemplate.opsForValue().get(RedisKeyConstant.ORDER_ID + id);
        //如果存在那么返回，如果不存在那么抛出异常，表示命中空缓存
        if (StrUtil.isNotBlank(json)){
            Orders orders = JSONUtil.toBean(json, Orders.class);
            return orders;
        }
        if (json != null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //实现缓存重建
            //获取互斥锁
        String lockKey = "lock:shop" + id;
        boolean isLock = tryLock(lockKey);
        Orders orders;
        try {
            //判断是否成功
            if (!isLock){
                //失败，休眠并重试
                Thread.sleep(50);
               return getById(id);
            }
            //成功，根据id查询数据


            orders = orderMapper.getById(id);

            //如果不存在,返回错误，并向缓存中写空值
            if (orders == null){
                redisTemplate.opsForValue().set(RedisKeyConstant.ORDER_ID+id,"",RedisKeyConstant.CANCEL_NULL, TimeUnit.SECONDS);
                throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
            }


            redisTemplate.opsForValue().set(RedisKeyConstant.ORDER_ID+id,orders,RedisKeyConstant.CANCEL_ORDER, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lockKey);
        }
        return orders;

    }

    private boolean tryLock(String key){
        Boolean b = redisTemplate.opsForValue().setIfAbsent(key, RedisKeyConstant.Lock, RedisKeyConstant.LOCK_CANCEL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }
    private void unLock(String key){
        redisTemplate.delete(key);
    }

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    private Orders getByIdWithLogicExpire(Long id){
        //先去缓存里面查
        String json = (String) redisTemplate.opsForValue().get(RedisKeyConstant.ORDER_ID + id);
        //如果不存在那么抛出异常，表示命中空缓存
        if (StrUtil.isBlank(json)){
            return null;
        }
        /*如果存在*/
        RedisData data = JSONUtil.toBean(json, RedisData.class);
        /*判断是否过期*/
        LocalDateTime timeout = data.getTimeout();
        if(timeout.isAfter(LocalDateTime.now())){
            return JSONUtil.toBean ((JSONObject) data.getObject(),Orders.class);
        }
        /*过期尝试获取锁*/
        String key = RedisKeyConstant.LOCK_KEY_ORDER + "id";
        boolean isLock = tryLock(key);
        if (isLock){
            try {
                /*获取成功，开启独立线程进行缓存修改，并返回数据，结束后释放锁*/
                CACHE_REBUILD_EXECUTOR.submit(()->{
                   //重建缓存
                    saveOrderRedis(id, 20L);
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unLock(key);
            }

        }


        /*获取失败，返回旧数据*/
        return JSONUtil.toBean ((JSONObject) data.getObject(),Orders.class);

    }

    private void saveOrderRedis(Long id,Long expireSeconds){
        Orders orders = orderMapper.getById(id);
        RedisData redisData = RedisData.builder()
                .timeout(LocalDateTime.now().plusSeconds(expireSeconds))
                .object(orders)
        .build();
        redisTemplate.opsForValue().set(RedisKeyConstant.ORDER_ID+id,JSONUtil.toJsonStr(redisData));
    }




}
